package com.xh.bussiness.permission.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.WxMaConfiguration;
import com.xh.bussiness.permission.model.Role;
import com.xh.bussiness.permission.model.School;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.model.UserLoginLog;
import com.xh.bussiness.permission.service.*;
import com.xh.bussiness.permission.util.UserAuthUtil;
import com.xh.bussiness.system.constant.UserOnlineConstant;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.*;
import com.xh.bussiness.weixin.service.IWeixinService;
import com.xh.core.annotation.ExcludeLoginTokenIntercept;
import com.xh.core.bean.AjaxResult;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.controller.BaseController;
import com.xh.core.properties.WxMaProperties;
import com.xh.core.properties.XhProperties;
import com.xh.core.util.*;
import com.xh.l.L;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;


@Api(tags = "认证接口")
@RestController
@RequestMapping("/permission/auth")
public class AuthController extends BaseController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private XhProperties xhProperties;
    @Autowired
    private IUserOnlineService userOnlineService;
    @Autowired
    private IUserLoginLogService userLoginLogService;
    @Autowired
    private IWeixinService weixinService;

    @Value("${xh.expires.publicKey}")
    private String publicKey;


    @ApiOperation(value = "用户账号密码登陆认证", notes = "用户账号密码登陆认证接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "md5Password", value = "MD5加密密码", required = true, dataType = "String")
    })
    @PostMapping("/login")
    @ExcludeLoginTokenIntercept
    public AjaxResult accountLogin(HttpServletRequest request, HttpServletResponse response, Integer loginType, String mobile, String md5Password) {
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");
        //验证账号是否到期
        if(!UserAuthUtil.checkExpireDate(publicKey)){
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "系统已到期，请联系管理员");
        }
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }

        if (user.getStatus().equals(1)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户已被禁用");
        }
        if (!UserAuthUtil.checkPassword(os, system, user.getId(), user.getPassword(), md5Password)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户名密码不匹配");
        }
        //userService.reloadUserData(user.getMobile(), user.getIdCard(), user);

        JSONObject result = getUserData(response, os, system, user);
        CacheUtils.set("user_" + user.getId(), JSONObject.toJSON(user));
        request.getSession().setAttribute("user", user);
        // 增加登录日志
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(user.getId());
        userLoginLog.setUserName(user.getNickname());
        userLoginLog.setIp(HttpUtils.getIpAdrress(request));
        userLoginLog.setModuleName(loginType == null || loginType == 1 ? "前台" : "后台" );
        userLoginLog.setBrowserInfo(request.getHeader("User-Agent"));
        userLoginLogService.insert(userLoginLog);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }

    @ApiOperation(value = "根据验证码登录", notes = "根据验证码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String")
    })
    @PostMapping("/loginByCode")
    @ExcludeLoginTokenIntercept
    public AjaxResult accountLoginByCode(HttpServletRequest request, HttpServletResponse response, String mobile, String code) {
        //添加特殊验证码

        Object o = CacheUtils.get("mobile_code_" + mobile);
        if (o == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "请发送验证码");
        }
        if (!o.toString().equals(code)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "验证码输入错误，请重新输入");
        }
        CacheUtils.delete("mobile_code_" + mobile);

        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        if (user.getStatus().equals(1)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户已被禁用");
        }
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");

        JSONObject result = getUserData(response, os, system, user);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }


    private JSONObject getUserData(HttpServletResponse response, Integer os, Integer system, User user) {
        CacheUtils.set("user_" + user.getId(), JSONObject.toJSON(user));

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

        JSONObject result = new JSONObject();

        List<Role> roles = userRoleService.queryRoleByUserId(user.getId());
        if (!CollectionUtils.isEmpty(roles)) {

        }
        //List<Map<String, Object>> menuFunctions = userRoleService.queryMenuFunctionsByUserId(user.getId());
       /* Map<String, Map<String, Object>> permisstions = new HashMap<>();
        if (menuFunctions != null) {
            for (Map<String, Object> item : menuFunctions) {
                String url = (String) item.get("url");
                String userFunctions = (String) item.get("user_functions");
                userFunctions = StringUtils.isEmpty(userFunctions) ? "" : userFunctions.trim();
                item.replace("user_functions", userFunctions);
                if (!StringUtils.isEmpty(url)) {
                    permisstions.put(url, item);
                }
            }
        }*/

        //处理菜单树
        /*JSONArray menusTree = new JSONArray();
        Predicate<Map<String, Object>> predicate = new Predicate<Map<String, Object>>() {
            @Override
            public boolean apply(Map<String, Object> input) {
                return StringUtils.isEmpty((String) input.get("parent_id"));
            }
        };
        Collection<Map<String, Object>> rootList = Collections2.filter(menuFunctions, predicate);
        rootList.stream().forEach(item -> {
            JSONObject node = (JSONObject) JSONObject.toJSON(item);
            node = findChild(node, menuFunctions);
            menusTree.add(node);
        });*/

        String accessToken = UserAuthUtil.generateToken(os, system, user.getId(), user.getUsername());

        // 更新数据库在线状态
        user.setOnline(UserOnlineConstant.ONLINE);

        //更新最近一次登录时间
        user.setLastLoginTime(new Date());
        userService.update(user);

        // 更新用户最后一次请求的标识
//        userOnlineService.updateLastRquest(user.getId(), false);

        result.put("user", user);
        result.put("accessToken", accessToken);
        result.put("menus", new ArrayList<>());
        result.put("menusTree", new ArrayList<>());
        result.put("roles", roles);
        return result;
    }

    @ApiOperation(value = "注册用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", required = true, dataType = "String"),
    })
    @PostMapping("/register")
    @Transactional
    @ExcludeLoginTokenIntercept
    public AjaxResult register(String mobile, String idCard) {
        /*boolean verify = L.verify();
        if (!verify) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "授权过期，请联系管理员");
        }*/
        Map<String, Object> registerInfo = userService.register(mobile, idCard);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, registerInfo);
    }


    /**
     * 发送验证码
     *
     * @param mobile
     * @return
     */
    @ApiOperation(value = "发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String")
    })
    @PostMapping("/sendCheckCode")
    @ExcludeLoginTokenIntercept
    public AjaxResult sendCheckCode(@RequestParam String mobile) throws Exception {
        if (StringUtils.isEmpty(mobile)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "手机号不能为空");
        }
        // 判断该用户是否存在
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        if (user.getStatus().equals(1)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户已被禁用");
        }

        String code = StringUtils.randomNumber(4);
        Integer result = MessageUtils.setCode(mobile, code);
//        Integer result = 200;
        System.out.println("mobile_code :" + code);
        if (result == 200) {
            //存入缓存有效期5分钟
            CacheUtils.set("mobile_code_" + mobile, code, 300000);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "发送成功");
        } else {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "验证码发送失败，请重试");
        }
    }

    /**
     * 校验验证码
     *
     * @param mobile
     * @param code
     * @return
     */
    @ApiOperation(value = "校验验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String")
    })
    @PostMapping("/validationCheckCode")
    @ExcludeLoginTokenIntercept
    public AjaxResult validationCheckCode(String mobile, String code) {
        if (!xhProperties.isSendMsg()) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
        }
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(code)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        //添加特殊验证码
        if (code.equals("9999")) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "验证成功");
        }
        Object o = CacheUtils.get("sendCheckCode_" + mobile);
        if (o == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "验证码验证失败，请重新发送");
        }
        if (!o.toString().equals(code)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "验证码输入错误，请重新输入");
        }
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "验证成功");
    }

    @ApiOperation(value = "重置密码", notes = "重置密码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String")
    })
    @PostMapping("/resetPassword")
    @ExcludeLoginTokenIntercept
    @Transactional
    public AjaxResult resetPassword(String mobile, String password) {
        /*boolean verify = L.verify();
        if (!verify) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "授权过期，请联系管理员");
        }*/
        //Todo
        User user = userService.getUserByMobile(mobile);
        if(user == null){
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        String newPassword = UserAuthUtil.encodePassword(user.getId(), password);
        user.setPassword(newPassword);
        userService.update(user);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
    }


    @ApiOperation(value = "修改密码", notes = "修改密码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassword", value = "老密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String")
    })
    @PostMapping("/changePassword")
    @Transactional
    public AjaxResult changePassword(HttpServletRequest request, String oldPassword, String newPassword) {
        User user = userService.getById(request.getHeader("userId"));
        if (user.getPassword().equals(UserAuthUtil.encodePassword(user.getId(), oldPassword))) {
            user.setPassword(UserAuthUtil.encodePassword(user.getId(), newPassword));
            userService.update(user);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "密码修改成功！");
        }
        return new AjaxResult(AjaxResultConstant.Result.ERROR, "旧密码错误");
    }

    @PostMapping("/updatePassword")
    @Transactional
    public AjaxResult updatePassword(String mobile, String code, String password) {
        Object o = CacheUtils.get("mobile_code_" + mobile);
        if (o == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "请发送验证码");
        }
        if (!o.toString().equals(code)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "验证码输入错误，请重新输入");
        }
        CacheUtils.delete("mobile_code_" + mobile);
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }else{
            user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(password)));
            userService.update(user);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, "密码修改成功！");
        }
    }


    @ApiOperation(value = "使用短信验证码更换手机号码", notes = "使用短信验证码更换手机号码接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "newMobile", value = "新手机号码", required = true, dataType = "String")
    })
    @PostMapping("/changeMobileByVerificationCode")
    @ExcludeLoginTokenIntercept
    @Transactional
    public AjaxResult changeMobileWithVerificationCode(HttpSession session, String verificationCode, String newMobile) {
        User user = (User) session.getAttribute("user");
        //Todo
        if (true) {
            user.setMobile(newMobile);
            userService.update(user);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS);
        }
        return new AjaxResult(AjaxResultConstant.Result.ERROR);
    }


    @ApiOperation(value = "用户退出", notes = "用户退出登录接口")
    @PostMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

        String userId = request.getHeader("userId");
        //User user = (User) request.getSession().getAttribute("user");
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");
        CacheUtils.delete("token_" + os + "_" + system + "_" + userId);
        //response.sendRedirect(request.getContextPath() + "/admin/toLogin");
        // 清掉用户最后一次请求的标识的缓存
        CacheUtils.delete(UserOnlineConstant.USER_LAST_RQUEST_KEY_PREFIX + userId);
    }

    /**
     * 菜单list转树状结构递归
     *
     * @param node
     * @param list
     * @return
     */
    private JSONObject findChild(JSONObject node, List<Map<String, Object>> list) {
        JSONArray childs = new JSONArray();
        for (Map<String, Object> item : list) {
            if (node.getString("id").equals((String) item.get("parent_id"))) {
                JSONObject child = (JSONObject) JSONObject.toJSON(item);
                childs.add(findChild(child, list));
            }
        }
        node.put("childs", childs);
        return node;
    }

    //
    @ApiOperation(value = "登录凭证校验", notes = "登录凭证校验")
    @PostMapping("/getWxLoginInfo")
    public AjaxResult getWxLoginInfo(HttpServletRequest request, String appid, String code) throws WxErrorException {
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        System.out.println("dddd--------code:"+code);
        WxMaJscode2SessionResult result = wxService.getUserService().getSessionInfo(code);
        Map<String, String> retMap = new HashMap<>();
//        retMap.put("sessionKey", result.getSessionKey());
//        retMap.put("openId", result.getOpenid());
        String accessToken = MD5Utils.string2MD5(result.getOpenid() + result.getSessionKey());
        retMap.put("accessToken", accessToken);
        CacheUtils.set(accessToken, result.getOpenid() + "&&" + result.getSessionKey());
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, retMap);
    }

    /**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     */
    @RequestMapping("/getWxUserPhone")
    public AjaxResult getWxUserPhone(HttpServletRequest request,String accessToken, String appid, String signature,
                                     String rawData, String encryptedData, String iv) {

//        // 用户信息校验
//        if (!wxMaService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
//            return "user check failed";
//        }
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        String sessionKey = ((String) CacheUtils.get(accessToken)).split("&&")[1];
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        String phone = phoneNoInfo.getPhoneNumber();
        User user = userService.getUserByMobile(phone);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");
        String userToken = UserAuthUtil.generateToken(os, system, user.getId(), user.getUsername());

        List<Student> students = studentService.queryByUserId(user.getId());
        if("家长".equals(user.getUsername()) && (students == null || students.size()==0)){
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("userInfo", user);
        result.put("students", students);
        result.put("accessToken", userToken);

        // 更新数据库在线状态
        user.setOnline(UserOnlineConstant.ONLINE);
        //更新最近一次登录时间
        user.setLastLoginTime(new Date());
        userService.update(user);
        // 更新用户最后一次请求的标识
        userOnlineService.updateLastRquest(user.getId(), false);

        CacheUtils.set("user_" + user.getId(), JSONObject.toJSON(user));
        request.getSession().setAttribute("user", user);

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }

    @ApiOperation(value = "小程序登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "md5Password", value = "md5值密码", required = true, dataType = "String"),
    })
    @PostMapping("/loginForApplet")
    @Transactional
    @ExcludeLoginTokenIntercept
    public AjaxResult loginForApplet(HttpServletRequest request, String mobile, String md5Password) {
        //验证账号是否到期
//        if(!UserAuthUtil.checkExpireDate(publicKey)){
//            return new AjaxResult(AjaxResultConstant.Result.ERROR, "账号已到期");
//        };
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(md5Password)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        if (!(UserAuthUtil.checkPassword(null, null, user.getId(), user.getPassword(), md5Password))) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "密码输入错误");
        }
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");
        String userToken = UserAuthUtil.generateToken(os, system, user.getId(), user.getUsername());
        // 更新数据库在线状态
        user.setOnline(UserOnlineConstant.ONLINE);
        //更新最近一次登录时间
        user.setLastLoginTime(new Date());
        userService.update(user);
        // 更新用户最后一次请求的标识
        userOnlineService.updateLastRquest(user.getId(), false);
        List<Student> students = studentService.queryByUserId(user.getId());
        if("家长".equals(user.getUsername()) && (students == null || students.size()==0)){
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "用户不存在");
        }
        Map<String, Object> result = new HashMap<>(2);
        result.put("userInfo", user);
        result.put("students", students);
        result.put("accessToken", userToken);

        CacheUtils.set("user_" + user.getId(), JSONObject.toJSON(user));
        request.getSession().setAttribute("user", user);

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }


    @ApiOperation(value = "小程序测评登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "studentName", value = "姓名", required = true, dataType = "String"),
    })
    @PostMapping("/loginForAppletEvaluating")
    @Transactional
    @ExcludeLoginTokenIntercept
    public AjaxResult loginForAppletEvaluating(HttpServletRequest request, String mobile, String studentName) {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(studentName)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            user.setUsername("家长");
            userService.insert(user);
            user.setPassword(UserAuthUtil.encodePassword(user.getId(), MD5Utils.string2MD5(user.getMobile())));
            userService.update(user);
        }
        List<Student> students = studentService.getStudentByUserId(user.getId());
        if (CollectionUtils.isEmpty(students)) {
            Student student = new Student();
            student.setUserId(user.getId());
            student.setIntentionStatus(1);
            student.setName(studentName);
            student.setNickname(studentName);
            student.setMotherPhone(mobile);

            studentService.insert(student);

            students.add(student);
        }
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");
        String userToken = UserAuthUtil.generateToken(os, system, user.getId(), user.getUsername());

        // 更新用户最后一次请求的标识
        userOnlineService.updateLastRquest(user.getId(), false);
        Map<String, Object> result = new HashMap<>(4);
        result.put("userInfo", user);
        result.put("students", students);
        result.put("accessToken", userToken);

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }

    @ApiOperation(value = "根据手机号查询用户信息，用于小程序测评")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "studentName", value = "姓名", required = true, dataType = "String"),
    })
    @PostMapping("/queryByMobile")
    @Transactional
    @ExcludeLoginTokenIntercept
    public AjaxResult queryByMobile(HttpServletRequest request, String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            return new AjaxResult(AjaxResultConstant.Result.ERROR, "参数错误");
        }
        User user = userService.getUserByMobile(mobile);
        if (user == null) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, null);
        }
        List<Student> students = studentService.getStudentByUserId(user.getId());
        if (CollectionUtils.isEmpty(students)) {
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS, null);
        }
        Integer os = request.getIntHeader("os");
        Integer system = request.getIntHeader("system");
        String userToken = UserAuthUtil.generateToken(os, system, user.getId(), user.getUsername());

        Map<String, Object> result = new HashMap<>(2);
        result.put("userInfo", user);
        result.put("students", students);
        result.put("accessToken", userToken);

        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, result);
    }

    @ApiOperation(value = "获取微信签名", notes = "获取微信签名")
    @RequestMapping("/getWxSignature")
    @ExcludeLoginTokenIntercept
    public AjaxResult getWxSignature(String url) {
        Map<String, Object> wxSignature = weixinService.getWxSignature(url);
        return new AjaxResult(AjaxResultConstant.Result.SUCCESS, wxSignature);
    }

}
